using System;
using System.Collections;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Resources;
using System.Threading;
using System.Web;
using System.Web.Security;
using ASPNETVN.PORTAL.Components.Configuration;
using ASPNETVN.PORTAL.Components.Security;


namespace ASPNETVN.PORTAL
{
    public class Global : HttpApplication
    {
        /// <summary>
        /// Portal ID.
        /// </summary>
        /// 
        public static Guid PortalID = new Guid(ConfigurationManager.AppSettings["PortalID"]);
        public static Guid DefaultTabID = new Guid(ConfigurationManager.AppSettings["DefaultTabID"]);

        public void UpdateVisitorCount()
        {
            PortalConfiguration.UpdateVisitorNumber(PortalID);

            //try
            //{
            //    int count = GetVisitorCount();
            //    count++;

            //    // Write to file.
            //    string filepath = Server.MapPath("~/App_Data/VisitorCount/" + PortalID + ".txt");
            //    using (StreamWriter streamWriter = File.CreateText(filepath))
            //    {
            //        streamWriter.Write(count);
            //        streamWriter.Close();
            //    }
            //}
            //catch
            //{
            //}
        }

        public static int GetVisitorCount()
        {
            return PortalConfiguration.GetVisitorNumber(PortalID);

            //try
            //{
            //    int? count = (int?)HttpContext.Current.Cache["VisitorCount"];
            //    if (count == null)
            //    {
            //        string filepath = HttpContext.Current.Server.MapPath("~/App_Data/VisitorCount/" + Global.PortalID + ".txt");
            //        using (StreamReader streamReader = File.OpenText(filepath))
            //        {
            //            string content = streamReader.ReadToEnd();
            //            count = Convert.ToInt32(content);
            //            streamReader.Close();
            //        }
            //        // Store the dataset in the cache
            //        HttpContext.Current.Cache.Insert("VisitorCount", count.Value, new CacheDependency(filepath));
            //    }
            //    return count.Value;
            //}
            //catch
            //{
            //}
            //return 0;
        }


        public void IncreaseOnlineCount()
        {
            Application["OnlineCount"] = Convert.ToInt32(Application["OnlineCount"]) + 1;
            //PortalConfiguration.IncreaseOnlineNumber(PortalID);
        }

        public void DecreaseOnlineCount()
        {
            Application["OnlineCount"] = Convert.ToInt32(Application["OnlineCount"]) - 1;
            PortalConfiguration.DecreaseOnlineNumber(PortalID);
        }

        /// <summary>
        /// Resource manager.
        /// </summary>
        public static ResourceManager RM = new ResourceManager("ASPNETVN.PORTAL.App_GlobalResources.Strings", typeof(Global).Assembly);

        protected void Session_Start(Object sender, EventArgs e)
        {
            UpdateVisitorCount();
            IncreaseOnlineCount();
        }

        protected void Session_End(Object sender, EventArgs e)
        {
            UpdateVisitorCount();
            DecreaseOnlineCount();
        }


        protected void Application_Start(Object sender, EventArgs e)
        {
            //RouteTable.Routes.AddCombresRoute("Combres Route");

            Application.Lock();
            Application["OnlineCount"] = 1;
            Application.UnLock();
        }

        protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            // BEGIN: Gzip.
            //HttpApplication app = (HttpApplication)sender;
            //string acceptEncoding = app.Request.Headers["Accept-Encoding"];
            //Stream prevUncompressedStream = app.Response.Filter;

            //if (string.IsNullOrEmpty(acceptEncoding))
            //    return;

            //acceptEncoding = acceptEncoding.ToLower();

            //if (acceptEncoding.Contains("gzip"))
            //{
            //    // gzip
            //    app.Response.Filter = new GZipStream(prevUncompressedStream,
            //        CompressionMode.Compress);
            //    app.Response.AppendHeader("Content-Encoding",
            //        "gzip");
            //}
            //else if (acceptEncoding.Contains("deflate"))
            //{
            //    // defalte
            //    app.Response.Filter = new DeflateStream(prevUncompressedStream,
            //        CompressionMode.Compress);
            //    app.Response.AppendHeader("Content-Encoding",
            //        "deflate");
            //}
            // END: Gzip.

            // Home TabID.
            Guid tabID = Global.DefaultTabID;

            // Get TabID from querystring
            if (Request.Params["tabid"] != null)
            {
                tabID = new Guid(Request.Params["tabid"]);
            }

            // Build and add the Portal object to the current Context
            Context.Items.Add("Portal", new Components.Configuration.Items.Portal(tabID));

            // Retrieve and add the Portal DataSet to the current Context
            //HttpContext.Current.Items.Add("PortalDataSet", PortalConfiguration.GetPortalDataSet());

            // Using for SOFTECH.Modules.ECDS
            // Build and add the DuLieuChuanDataSet, WebServiceListDataSet to the current Context
            //HttpContext.Current.Items.Add("DuLieuChuanDataSet", DuLieuChuanHelper.GetDuLieuChuanDataSet());
            //HttpContext.Current.Items.Add("WebServiceListDataSet", WebServiceListHelper.GetWebServiceListDataSet());

            // Language.
            Components.Configuration.Items.Portal portal = (Components.Configuration.Items.Portal)HttpContext.Current.Items["Portal"];
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(portal.Language);
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(portal.Language);
        }

        protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            /*
            if (HttpContext.Current.User != null)
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    if (HttpContext.Current.User.Identity is FormsIdentity)
                    {
                        FormsIdentity id = (FormsIdentity) HttpContext.Current.User.Identity;
                        FormsAuthenticationTicket ticket = id.Ticket;

                        // Get the stored user-data, in this case, our roles.
                        string userData = ticket.UserData;
                        string[] roles = userData.Split(';');

                        PortalSecurity.CurrentUser = new PortalPrincipal(Context.User.Identity, roles);
                    }
                }
            }
            */
            if (Request.IsAuthenticated)
            {
                string[] roles;

                // Create the roles cookie if it doesn't exist yet for this session.
                if ((Request.Cookies["portalroles"] == null) || (Request.Cookies["portalroles"].Value == ""))
                {
                    // Get roles from UserRoles table, and add to cookie
                    roles = Components.Security.User.GetRoles(PortalSecurity.CurrentUser.Identity.ID);

                    // Create a string to persist the roles
                    string roleStr = "";
                    foreach (string role in roles)
                    {
                        roleStr += role;
                        roleStr += ";";
                    }

                    // Create a cookie authentication ticket.
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                        1, // version
                        PortalSecurity.CurrentUser.Identity.ToString(), // user name
                        DateTime.Now, // issue time
                        DateTime.Now.AddMinutes(1), // expires every minute
                        false, // don't persist cookie
                        roleStr // roles
                        );

                    // Encrypt the ticket
                    string cookieStr = FormsAuthentication.Encrypt(ticket);

                    // Send the cookie to the client
                    Response.Cookies["portalroles"].Value = cookieStr;
                    Response.Cookies["portalroles"].Path = "/";
                    Response.Cookies["portalroles"].Expires = DateTime.Now.AddMinutes(1);
                }
                else
                {
                    // Get roles from roles cookie
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies["portalroles"].Value);

                    //convert the string representation of the role data into a string array
                    ArrayList userRoles = new ArrayList();

                    foreach (string role in ticket.UserData.Split(new[] { ';' }))
                    {
                        userRoles.Add(role);
                    }

                    roles = (string[])userRoles.ToArray(typeof(string));
                }

                // Add our own custom principal to the request containing the roles in the auth ticket
                PortalSecurity.CurrentUser = new PortalPrincipal(Context.User.Identity, roles);
            }
        }
        public static string GetApplicationPath()
        {
            string path = string.Empty;
            try
            {
                if (HttpContext.Current.Request.ApplicationPath != "/")
                    path = HttpContext.Current.Request.ApplicationPath;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }

            return path;
        }

        //*********************************************************************
        //
        // GetApplicationPath Method
        //
        // This method returns the correct relative path when installing
        // the portal on a root web site instead of virtual directory
        //
        //*********************************************************************
        public static string GetApplicationPath(HttpRequest request)
        {
            string path = string.Empty;
            try
            {
                if (request.ApplicationPath != "/")
                    path = request.ApplicationPath;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }

            return path;
        }

        public static string GetMasterFile()
        {
            const string masterfile = "Office";
            Components.Configuration.Items.Portal portal = HttpContext.Current.Items["Portal"] as Components.Configuration.Items.Portal;
            if (portal != null)
            {
                if (!string.IsNullOrEmpty(portal.ActiveTab.ThemeName))
                    return portal.Layout;
            }
            return masterfile;
        }

        public static string GetThemeName()
        {
            const string themeName = "Blue";
            Components.Configuration.Items.Portal portal = HttpContext.Current.Items["Portal"] as Components.Configuration.Items.Portal;
            if (portal != null)
            {
                if (!string.IsNullOrEmpty(portal.ActiveTab.ThemeName))
                    return portal.ActiveTab.ThemeName;
                return portal.DefaultTheme;
            }
            return themeName;
        }
    }
}